//
//  MaterialInterfaceViewController.m
//  ProjectA
//
//  Created by 李赐岩 姜雪 张昕锐 on 15/3/5.
//  Copyright (c) 2015年 李赐岩 姜雪 张昕锐. All rights reserved.
//

#import "MaterialInterfaceViewController.h"

@interface MaterialInterfaceViewController ()

@end

@implementation MaterialInterfaceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = @"分类";
    
    // 网络判断 wifi  3g 有网时可以数据请求
    self.classDic = [NSMutableDictionary dictionary];
    self.classArray = [NSMutableArray array];
    
    [[materialDataBase shareClassifyDataBaseHandle] openDB];
    [[materialDataBase shareClassifyDataBaseHandle] createTable];
    [AFNDownLoader getDataDownLoad:@"http://68.168.105.137/cookbook/master/master.php?email=&appname=com.riatech.cookbook&country=CN&devid=20e94d365e82aa2f&simcountry=cn&version=7.9.2&versioncode=40&lang=zh-CN&inputlang=zh-CN" block:^(id myData) {
        
        NSMutableDictionary *Bigdic = myData;
        NSMutableArray *array = [Bigdic objectForKey:@"tiles"];
        NSLog(@"dadada%@", array);
        
        [[materialDataBase shareClassifyDataBaseHandle] deleteTable];
        [[materialDataBase shareClassifyDataBaseHandle] createTable];
        
       
        
        for (NSMutableDictionary *dic in array) {
            
            MaterialModel *material = [[MaterialModel alloc] init];
            material.name = [dic objectForKey:@"name"];
            material.url = [dic objectForKey:@"url"];
            material.thumb = [dic objectForKey:@"thumb"];
            [material setValuesForKeysWithDictionary:dic];
            [[materialDataBase shareClassifyDataBaseHandle] insertMaterial:material];
            for (MaterialModel *material in [[materialDataBase shareClassifyDataBaseHandle] selectClassify]) {
                if ([material.name isEqualToString:@"牛肉"] || [material.name isEqualToString:@"海鲜"]) {
                    [[materialDataBase shareClassifyDataBaseHandle] deleteClassify:material.number];
                }
            }

            
        }
        self.classArray = [NSMutableArray arrayWithArray:[[materialDataBase shareClassifyDataBaseHandle] selectClassify ]];
        
        [self.collectionView reloadData];
        
        // 数据请求完毕 取消菊花
        [self.HUD removeFromSuperview];
        
    }];
    
    UICollectionViewFlowLayout *viewLayout = [[UICollectionViewFlowLayout alloc] init];
    // 设置item大小
    viewLayout.itemSize = CGSizeMake(self.view.frame.size.width / 4, self.view.frame.size.height / 5.5);
    // 设置滑动方向
    viewLayout.scrollDirection = UICollectionViewScrollPositionCenteredVertically;
    // 设置边距
    viewLayout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    // 设置距离底部距离
    viewLayout.footerReferenceSize = CGSizeMake(50, 50);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:viewLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    
    // 菊花
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
   self.HUD.labelText = @"Loading";
    [self.HUD showAnimated:YES whileExecutingBlock:^{
        
        [self showtime];
    } completionBlock:^{
        
        
    }];
    
    // 注册cell
    [self.collectionView registerClass:[MaterialCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
}

-(void)showtime
{
    sleep(10);
}


// 设置collection个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
   return [[materialDataBase shareClassifyDataBaseHandle] selectClassify].count - 2;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MaterialCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    MaterialModel *material = [ [[materialDataBase shareClassifyDataBaseHandle] selectClassify] objectAtIndex:indexPath.row + 2];
    NSString *urlstr = [material.thumb stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:urlstr];
    [cell.collectionView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder_Phone@2x.png"]];
    cell.collectionLabel.text = material.name;
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    if ([wifi currentReachabilityStatus] == NotReachable || [conn currentReachabilityStatus] == NotReachable) {
        UIAlertView *alterView = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"网络不佳, 请稍后重试" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alterView show];
    }
    MenuViewController *menuVC = [[MenuViewController alloc] init];
    MaterialModel *material = [[[materialDataBase shareClassifyDataBaseHandle] selectClassify] objectAtIndex:indexPath.row + 2];
    menuVC.urlString = material.url;
    menuVC.titleString = material.name;
    [self.navigationController pushViewController:menuVC animated:YES];
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view  controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
